<?php

/**
 *  天气类
 */
class weatherModel
{

    private $redis_key = '';

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        $this->redis_key = REDIS_PREFIX . 'weather_';
        $this->redis_need_up_key = REDIS_PREFIX . 'update';
        $this->weatherValidTime = 6 * 3600;
        $this->weatherOverLine= 86400 - $this->weatherValidTime;
    }

    /**
     * 运动建议相关设置
     */
    static $weekarray=array("日","一","二","三","四","五","六");
    static $adviseWords = array('100' => 1,
                                '101' => 1,
                                '102' => 1,
                                '200' => 2,
                                '201' => 3,
                                '202' => 3,
                                '300' => 2,
                                '301' => 4,
                                '302' => 5,
                                '400' => 2,
                                '401' => 6,
                                '402' => 7,
                                '500' => 2,
                                '501' => 8,
                                '502' => 8
                                );
    static $levelWords =  array('1'  => '不适宜',
                                '2'  => '不太适宜',
                                '3'  => '比较适宜',
                                '4'  => '适宜',
                                '5'  => '非常适宜 '
                            );
    static $allAdiviceWords = array('1' => array('0' =>'出去运动关注天气变化，做好防护措施呦！',
                                                 '1' =>'出去运动关注天气变化，做好防护措施呦！'),
                                    '2' => array('0' =>'偷得浮生半日闲。空气糟糕，小伙伴们室内活动吧！',
                                                 '1' =>'别忧伤，明日空气好，我们把今天补回来。'),
                                    '3' => array('0' =>'天气不太好，小伙伴们出门运动要三思呦！',
                                                 '1' =>'天气不太好，小伙伴们出门运动要三思呦！'),
                                    '4' => array('0' =>'忘了汗流浃背的快感？快拉上好朋友去跑步找回久违的酣畅淋漓！',
                                                 '1' =>'不忘初心，不悔始终，在奔跑的路上看最美的风景，欣赏最好的自己！'),
                                    '5' => array('0' =>'跑跑步吸吸氧，生命不休，运动不止，Come On！',
                                                 '1' =>'小伙伴们都运动去了，你还犹豫？健人就是要脚勤！'),
                                    '6' => array('0' =>'跑跑步，吸吸氧，生命在于运动，约上跑友去运动吧！',
                                                 '1' =>'小伙伴们都运动去了，你还犹豫？健人就是要脚勤！'),
                                    '7' => array('0' =>'空气如此好，不运动真是暴殄天物，去跑步享受运动的快乐吧！',
                                                 '1' =>'空气给力、天气不错，此时不跑更待何时，且跑且珍惜！'),
                                    '8' => array('0' =>'日观天象，不运动，必后悔，拉上好盆友去跑步吧！',
                                                 '1' =>'天气给力、空气又好，此时不动更待何时，且跑且珍惜')
                                    );
    /**
     * 返回所有城市列表
     * @return array
     */
    public function getAllCity()
    {
        $cityData = $this->db->getAll('select city_id_new as city_id,city from r_city');
        return $cityData;
    }
    public function insertWeather($data)
    {
        //更新redis的天气数据
        if(empty($data['city_id'])) return false;
        $city_id = $data['city_id'];
        $this->redis->sismember($this->redis_need_up_key, $city_id) && $this->redis->srem($this->redis_need_up_key, $city_id);
        return $this->redis->set($this->redis_key. $data['city_id'], json_encode($data), 86400) != false;
    }

    /**
     * 获取某个城市天气信息
     * @param type $city_id
     */
    public function getWeatherInfo($city_id)
    {
        $json_str = '';

        if (!$this->redis->exists($this->redis_key.$city_id))
        {
            $weather = $this->getWeather($city_id);
            !empty($weather) && $this->insertWeather($weather);
        }
        else
        {
            $expire_time = $this->redis->ttl($this->redis_key.$city_id);
            if($expire_time < $this->weatherOverLine)// 过期
            {
                $this->redis->sadd($this->redis_need_up_key, $city_id);
            }
        }
        $json_str = $this->redis->get($this->redis_key. $city_id);
        return json_decode($json_str, TRUE);
    }

    /**
     * 更新城市天气信息
     * @param type $city_id
     */
    public function getWeather($city_id)
    {
        $weather = array();
        $url = "https://api.thinkpage.cn/v2/weather/all.json";
        $params = array('language'  =>  'zh-chs',
                        'unit'      =>  'c',
                        'aqi'      =>  'city',
                        'city'     =>  $city_id,
                        'key'      =>  '5FCI3NGCHO'
            );
        $data = common::getContents($url, $params);
        $data = json_decode($data, TRUE);
        if (!isset($data['status']) || $data['status'] != 'OK' || !isset($data['weather']))
        {
            return NULL;
        }
        $weather_data = $data['weather'][0];
        $weather['city_id'] = isset($weather_data['city_id']) ? $weather_data['city_id'] : $city_id;
        $weather['city_name'] = isset($weather_data['city_name']) ? $weather_data['city_name'] : '未知';
        $last_update = isset($weather_data['last_update']) ? $weather_data['last_update'] : '';
        $last_update = empty($last_update) ? time()-2*3600 : strtotime($last_update);
        $weather['last_update'] = date('n月j日 H:i:s', $last_update) .' 周' . self::$weekarray[date("w",$last_update)];
        $weather['text'] = isset($weather_data['now']['text']) ? $weather_data['now']['text'] : '';
        $weatherImgCode = isset($weather_data['now']['code']) ? $weather_data['now']['code'] : 99;
        $weather['code'] = $weatherImgCode;
        // $weather['weatherImg'] = 'http://image.thinkpage.cn/weather/images/icons/3d_50/'.$weatherImgCode.'.png';
        $weather['temperature'] = isset($weather_data['now']['temperature']) ? $weather_data['now']['temperature'] : '';
        $weather['wind_scale'] = isset($weather_data['now']['wind_scale']) ? $weather_data['now']['wind_scale'] : '';
        $weather['wind_direction'] = isset($weather_data['now']['wind_direction']) ? $weather_data['now']['wind_direction'] : '';
        $weather['humidity'] = isset($weather_data['now']['humidity']) ? $weather_data['now']['humidity'] : '';
        $weather['sunrise'] = isset($weather_data['today']['sunrise']) ? $weather_data['today']['sunrise'] : '';
        $weather['sunset'] = isset($weather_data['today']['sunset']) ? $weather_data['today']['sunset'] : '';
        $weather['uvbrief'] = isset($weather_data['today']['suggestion']['uv']['brief']) ? $weather_data['today']['suggestion']['uv']['brief'] : '';
        $weather['pm25'] = isset($weather_data['now']['air_quality']['city']['pm25']) ? $weather_data['now']['air_quality']['city']['pm25'] : 0;
        $visibility = isset($weather_data['now']['visibility']) ? $weather_data['now']['visibility'] : 0;
        $advise = $this->getAdvise($weatherImgCode, $weather['temperature'],$weather['humidity'],$weather['wind_scale'], $visibility, $weather['pm25']);
        $weather['advise'] = $advise['words'];
        $weather['weatherLevel'] = $advise['weatherLevel'];
        switch ($weather['pm25'])
        {
            case $weather['pm25'] <=35:
                $weather['pm25Info'] = $weather['pm25'].' 优';
                break;
            case $weather['pm25'] >35 && $weather['pm25'] <=70:
                $weather['pm25Info'] = $weather['pm25'].' 良';
                break;
            case $weather['pm25'] >70 && $weather['pm25'] <=115:
                $weather['pm25Info'] = $weather['pm25'].' 轻度污染';
                break;
            case $weather['pm25'] > 115 && $weather['pm25'] <=150:
                $weather['pm25Info'] = $weather['pm25'].' 中度污染';
                break;
            case $weather['pm25'] >150 && $weather['pm25'] <=250:
                $weather['pm25Info'] = $weather['pm25'].' 重度污染';
                break;
            case $weather['pm25'] >250:
                $weather['pm25Info'] = $weather['pm25'].' 严重污染';
                break;
            default:
                $weather['pm25Info'] = '真心搞不懂这是什么PM2.5';
                break;
        }
        $weather['uvInfo'] = '紫外线 '.$weather['uvbrief'];
        $weather['humidityInfo'] = '湿度 '.$weather['humidity'].'%';
        $weather['windInfo'] = $weather['wind_direction'].'风 '.$weather['wind_scale'].'级';
        $future = isset($weather_data['future']) ? $weather_data['future'] : array();
        if($future)
        {
            $i=0;
            foreach($future as $key=>& $v)
            {
                $v['formatDate'] = date('n月j日', strtotime($v['date'])) . ' '.$v['day'];
                if($i == 0 || $i >3)
                {
                    unset($future[$key]);
                }
                $i++;
            }
            $future = array_values($future);
        }
        $weather['future'] = $future;

        return $weather;
    }

    /**
     * 获取运动建议
     * @param  $weatherImgCode 天气情况代码
     * @param  $temperature  温度
     * @param  $humidity 湿度。单位：百分比%
     * @param  $wind_scale 风力等级。根据风速计算的风力等级
     * @param  $visibility 能见度。单位：公里km
     * @param  $pm25 PM2.5颗粒物（粒径小于等于2.5μm）1小时平均值。单位：μg/m³
     * @return   array()
     */
    public function getAdvise($weatherImgCode,$temperature, $humidity,$wind_scale,$visibility,$pm25)
    {
        // 获取K值
        $textLevel = 0;
        if($weatherImgCode < 9)
        {
            $textLevel = 2;
        }
        elseif($weatherImgCode == 9)
        {
            $textLevel = 1;
        }
        $temperatureLevel = 0;
        if(($temperature >-4 && $temperature <=0) || ($temperature >30 && $temperature <= 34))
        {
            $temperatureLevel = 1;
        }
        elseif($temperature >0 && $temperature <= 30)
        {
            $temperatureLevel = 2;
        }
        $humidityLevel = 1;
        if($humidity >=35 && $humidity < 75)
        {
            $humidityLevel = 2;
        }
        $wind_scaleLevel = 0;
        if($wind_scale <= 4)
        {
            $wind_scaleLevel = 2;
        }
        elseif($wind_scale >4 && $wind_scale <= 7)
        {
            $wind_scaleLevel = 1;
        }
        $visibilityLevel = 0;
        if($visibility >=1 || $visibilityLevel == '未知')
        {
            $visibilityLevel = 1;
        }
        $k = $textLevel * $temperatureLevel * $humidityLevel * $wind_scaleLevel * $visibilityLevel;
        switch ($k) {
            case 0:
                $k_level = 100;
                break;
            case 1:
                $k_level = 200;
                break;
            case 2:
                $k_level = 300;
                break;
            case 4:
                $k_level = 300;
                break;
            case 8:
                $k_level = 400;
                break;
            case 16:
                $k_level = 500;
                break;
            default:
                $k_level = 100;
                break;
        }
        //获取P值
        $p_level = 0;
        if($pm25 <= 70)
        {
            $p_level = 2;
        }
        elseif($pm25 <= 150)
        {
            $p_level=1;
        }

        $words_key = self::$adviseWords[$k_level + $p_level];
        $words = self::$allAdiviceWords[$words_key];

        if($words)
        {
            $randKey = rand(0,1);
            return array('weatherLevel' => floor($k_level/100), 'words' => $words[$randKey]);
        }
        return array('weatherLevel' => 0, 'words' =>"今天跑不跑，除了看天气，也可以看心情！");
    }
}
?>